#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : lee

import sys
import os
import logging
import re
from SceneCheckTool.checkScript.CheckBase import CheckBase

try:
    import maya.cmds as cmds
    import pymel.core as pm
    import jarryLibs.mayakit.MayaUtils as mu
    reload(mu)
except:
    pass

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class CfxReferenceOfGrowMeshCheck(CheckBase):
    def __init__(self):
        super(CfxReferenceOfGrowMeshCheck, self).__init__()
        pass

    def check_reference_connection(self):
        # 通过文件名称获取资产信息
        maya_file = mu.sceneName()
        file_name = os.path.basename(maya_file)
        asset_short_type = file_name.split("_")[0]
        asset_name = file_name.split("_")[1]

        miss_node = []
        reference_group = "{0}_{1}_referenceMesh_grp".format(asset_short_type, asset_name)
        reference_mesh_node = self.get_reference_mesh_nodes()
        for node in reference_mesh_node:
            if not cmds.listRelatives(node, p=1):
                miss_node.append(node)
                continue
            if cmds.listRelatives(node, p=1)[0] != reference_group:
                miss_node.append(node)

        return miss_node

    def get_no_ref_growMesh_nodes(self):
        miss_nodes = []
        grow_mesh_nodes = self.get_grow_mesh_nodes()
        for node in grow_mesh_nodes:
            if not cmds.listConnections(node + ".referenceObject"):
                miss_nodes.append(node)
        return miss_nodes

    def get_reference_mesh_nodes(self):
        reference_mesh_nodes = []
        grow_mesh_nodes = self.get_grow_mesh_nodes()
        for node in grow_mesh_nodes:
            reference_node = cmds.listConnections(node + ".referenceObject")[0]
            reference_mesh_nodes.append(reference_node)
        return reference_mesh_nodes

    def check_grow_mesh_nodes_right(self):
        # 通过文件名称获取资产信息
        maya_file = mu.sceneName()
        file_name = os.path.basename(maya_file)
        asset_short_type = file_name.split("_")[0]
        asset_name = file_name.split("_")[1]

        miss_node = []
        growMesh_group = "{0}_{1}_growMesh_grp".format(asset_short_type, asset_name)
        grow_mesh_nodes = self.get_grow_mesh_nodes()
        for node in grow_mesh_nodes:
            if not cmds.listRelatives(node, p=1):
                miss_node.append(node)
                continue
            node_parent = cmds.listRelatives(node, p=1)[0]
            if node_parent != growMesh_group:
                miss_node.append(node)

        return miss_node

    def check_mesh_topo(self):
        miss_nodes = []
        ref_nodes_lib = {}
        grow_mesh_nodes = self.get_grow_mesh_nodes()
        for node in grow_mesh_nodes:
            reference_node = cmds.listConnections(node + ".referenceObject")[0]
            if mu.get_topo_info(node) != mu.get_topo_info(reference_node):
                miss_nodes.append(reference_node)
                ref_nodes_lib[reference_node] = node
        return miss_nodes, ref_nodes_lib

    def get_grow_mesh_nodes(self):
        pgYetiMaya_nodes = self.get_pgYetiMaya_nodes()

        grow_mesh_nodes = []
        for pgYeti_node in pgYetiMaya_nodes:
            try:
                grow_mesh = cmds.listConnections(pgYeti_node + ".inputGeometry[0]", d=1)[0]
                if grow_mesh not in grow_mesh_nodes:
                    grow_mesh_nodes.append(grow_mesh)
            except:
                continue
        return grow_mesh_nodes

    def get_pgYetiMaya_nodes(self):
        # 通过文件名称获取资产信息
        maya_file = mu.sceneName()
        file_name = os.path.basename(maya_file)
        asset_short_type = file_name.split("_")[0]
        asset_name = file_name.split("_")[1]

        pgYetiMaya_shapenodes = []
        groups_type = ["pgYetiMaya_dyn", "pgYetiMaya_static"]
        for type in groups_type:
            pgYetiMaya_group = "{0}_{1}_{2}_grp".format(asset_short_type, asset_name, type)
            if cmds.objExists(pgYetiMaya_group):
                for node in cmds.listRelatives(pgYetiMaya_group, c=True):
                    if cmds.listRelatives(node, s=True, c=True):
                        for shape_node in cmds.listRelatives(node, s=True, c=True):
                            if cmds.nodeType(shape_node) == "pgYetiMaya":
                                pgYetiMaya_shapenodes.append(node)

        return pgYetiMaya_shapenodes

    def check_groups_integrity(self):
        # 通过文件名称获取资产信息
        maya_file = mu.sceneName()
        file_name = os.path.basename(maya_file)
        asset_short_type = file_name.split("_")[0]
        asset_name = file_name.split("_")[1]

        cfx_group = "cfx_grp"
        dyn_group = "{0}_{1}_pgYetiMaya_dyn_grp".format(asset_short_type, asset_name)
        static_group = "{0}_{1}_pgYetiMaya_static_grp".format(asset_short_type, asset_name)
        growMesh_group = "{0}_{1}_growMesh_grp".format(asset_short_type, asset_name)
        reference_group = "{0}_{1}_referenceMesh_grp".format(asset_short_type,asset_name)

        if not cmds.objExists(cfx_group):
            return u"{0}组不存在，请检查当前文件的组命名是否正确。".format(cfx_group)
        if not cmds.objExists(dyn_group):
            return u"{0}组不存在，请检查当前文件的组命名是否正确。".format(dyn_group)
        if not cmds.objExists(static_group):
            return u"{0}组不存在，请检查当前文件的组命名是否正确。".format(static_group)
        if not cmds.objExists(growMesh_group):
            return u"{0}组不存在，请检查当前文件的组命名是否正确。".format(growMesh_group)
        if not cmds.objExists(reference_group):
            return u"{0}组不存在，请检查当前文件的组命名是否正确。".format(reference_group)
        return None

    def create_ref(self, source_node):
        # 通过文件名称获取资产信息
        maya_file = mu.sceneName()
        file_name = os.path.basename(maya_file)
        asset_short_type = file_name.split("_")[0]
        asset_name = file_name.split("_")[1]

        reference_group = "{0}_{1}_referenceMesh_grp".format(asset_short_type, asset_name)

        cmds.select(source_node, r=True)
        cmds.CreateTextureReferenceObject(source_node)
        new_ref_node = cmds.listRelatives(source_node, p=True)[0] + "_reference"
        cmds.parent(new_ref_node, reference_group, relative=1)

    def parent_growMesh_nodes(self, growMesh_nodes):
        # 通过文件名称获取资产信息
        maya_file = mu.sceneName()
        file_name = os.path.basename(maya_file)
        asset_short_type = file_name.split("_")[0]
        asset_name = file_name.split("_")[1]

        growMesh_group = "{0}_{1}_growMesh_grp".format(asset_short_type, asset_name)

        for node in growMesh_nodes:
            cmds.parent(node, growMesh_group, relative=1)

    def parent_ref_nodes(self, ref_nodes):
        # 通过文件名称获取资产信息
        maya_file = mu.sceneName()
        file_name = os.path.basename(maya_file)
        asset_short_type = file_name.split("_")[0]
        asset_name = file_name.split("_")[1]

        reference_group = "{0}_{1}_referenceMesh_grp".format(asset_short_type, asset_name)

        for ref_node in ref_nodes:
            cmds.parent(ref_node, reference_group, relative=1)

    def check(self):
        # 检查是否组是否存在
        result_proc = self.check_groups_integrity()
        if result_proc:
            result_log = u'Error:%s\n' % result_proc
            return result_log

        # 检查GrowMesh是否存在ref节点
        result_proc = self.get_no_ref_growMesh_nodes()
        if result_proc:
            result_log = u'Error:%s\nGrowMesh缺少ref节点' % result_proc
            return result_log

        # 检查分组是否匹配
        result_proc = self.check_grow_mesh_nodes_right()
        if result_proc:
            result_log = u'Error:%s\nGrowMesh的分组不匹配' % result_proc
            return result_log

        # 检查reference mesh节点拓扑是否存在问题
        result_proc, miss_topo_nodes = self.check_mesh_topo()
        if result_proc:
            result_log = u'Error:%s\nreference拓扑不匹配' % result_proc
            return result_log

        result_proc = self.check_reference_connection()
        if result_proc:
            result_log = u'Error:%s\nreference位置不匹配' % result_proc
        else:
            result_log = u'Succeed:没有问题\n'

        return result_log

    def fix(self):
        # 检查是否组是否存在
        result_proc = self.check_groups_integrity()
        if result_proc:
            result_log = u'Error:%s\n' % result_proc
            return result_log

        try:
            # 检查GrowMesh是否存在ref节点
            result_proc = self.get_no_ref_growMesh_nodes()
            if result_proc:
                for node in result_proc:
                    self.create_ref(node)
        except:
            result_proc = self.get_no_ref_growMesh_nodes()
            if result_proc:
                result_log = u'Error:%s\nGrowMesh缺少ref节点' % result_proc
                return result_log

        try:
            # 检查分组是否匹配
            result_proc = self.check_grow_mesh_nodes_right()
            if result_proc:
                self.parent_growMesh_nodes(result_proc)
        except:
            result_proc = self.check_grow_mesh_nodes_right()
            if result_proc:
                result_log = u'Error:%s\nGrowMesh的分组不匹配' % result_proc
                return result_log

        try:
            # 检查reference mesh节点拓扑是否存在问题
            result_proc, miss_topo_nodes = self.check_mesh_topo()
            if result_proc:
                for ref_node in miss_topo_nodes:
                    source_node = miss_topo_nodes[ref_node]
                    cmds.DeleteTextureReferenceObject(source_node)
                    cmds.delete(ref_node)
                    self.create_ref(source_node)
        except:
            result_proc, miss_topo_nodes = self.check_mesh_topo()
            if result_proc:
                result_log = u'Error:%s\nreference拓扑不匹配' % result_proc
                return result_log

        try:
            result_proc = self.check_reference_connection()
            if result_proc:
                self.parent_ref_nodes(result_proc)
        except:
            result_proc = self.check_reference_connection()
            if result_proc:
                result_log = u'Error:%s\n' % result_proc
                return result_log

        return u'Succeed:没有问题\n'